package pkg

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

func BindJson(c *gin.Context, obj interface{}) bool {
	if err := c.ShouldBindJSON(obj); err != nil {
		c.JSON(200, gin.H{"msg": err.Error(), "status": http.StatusBadRequest})
		return true
	}
	return false
}
func SmartUpdate(db *gorm.DB, c *gin.Context, modelPtr interface{}, idField string) {
	var jsonMap map[string]interface{}
	if BindJson(c, &jsonMap) {
		return
	}
	idValue, ok := jsonMap["goodsId"]

	if !ok {
		c.JSON(200, gin.H{"msg": "缺少ID字段", "status": http.StatusBadRequest})
		return
	}
	delete(jsonMap, idField)
	if len(jsonMap) == 0 {
		c.JSON(200, gin.H{"msg": "没有字段需要更新", "status": 2000})
		return
	}
	if err := db.Model(modelPtr).Where(idField+" = ?", idValue).Updates(jsonMap).Error; err != nil {
		c.JSON(200, gin.H{"msg": err.Error(), "status": http.StatusInternalServerError})
		return
	}
	c.JSON(200, gin.H{"msg": "更新成功", "status": http.StatusOK})
}
